package cn.hl.pet.service.impl;

import cn.hl.basic.exception.BusinessException;
import cn.hl.basic.service.IBaiduAiAuditService;
import cn.hl.basic.service.impl.BaseServiceImpl;
import cn.hl.basic.util.*;
import cn.hl.order.domain.OrderPetAcquisition;
import cn.hl.order.mapper.OrderPetAcquisitionMapper;
import cn.hl.org.domain.Employee;
import cn.hl.org.domain.Shop;
import cn.hl.org.mapper.EmployeeMapper;
import cn.hl.org.mapper.ShopMapper;
import cn.hl.pet.domain.Pet;
import cn.hl.pet.domain.SearchMasterMsg;
import cn.hl.pet.domain.SearchMasterMsgAuditLog;
import cn.hl.pet.mapper.PetMapper;
import cn.hl.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.hl.pet.mapper.SearchMasterMsgMapper;
import cn.hl.pet.query.SearchMasterMsgQuery;
import cn.hl.pet.service.ISearchMasterMsgService;
import cn.hl.user.domain.Logininfo;
import cn.hl.user.domain.User;
import cn.hl.user.mapper.UserMapper;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    @Transactional
    public AjaxResult publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        // 1.获取userId
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.findByLogininfoId(logininfo.getId());
        // 2.添加寻主消息
        searchMasterMsg.setUserId(user.getId());
        searchMasterMsgMapper.add(searchMasterMsg);
        // 3.百度智能审核文字和图片
        Boolean boo1 = baiduAiAuditService.textAudit(searchMasterMsg.getName() + searchMasterMsg.getTitle());
        Boolean boo2 = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());
        if (boo1 && boo2) {
            // 4.1审核通过，修改状态和日志
            searchMasterMsg.setState(1);
            searchMasterMsg.setNote("审核通过");
            // 4.2.1为寻主消息分配店铺 绑定店铺
            Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
            // 4.2.2寻找最近的店铺 50公里内
            Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.findAll());
            // 4.3如果寻找到店铺，修改shopId,给店铺主人发送短信通知
            if (nearestShop != null) {
                searchMasterMsg.setShopId(nearestShop.getId());
//                Employee employee = employeeMapper.findById(nearestShop.getAdminId());
//                SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请尽快处理：" + searchMasterMsg.getTitle());
                System.out.println("你有新的订单，请尽快处理：" + searchMasterMsg.getTitle());
            }
            // 4.4修改寻主消息
            searchMasterMsgMapper.update(searchMasterMsg);
            // 4.5添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            log.setState(1);
            log.setNote("审核成功");
            searchMasterMsgAuditLogMapper.add(log);
            // 4.6返回成功信息
            return new AjaxResult();
        } else {
            // 5.1审核不通过，添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            log.setState(0);
            log.setNote("审核失败");
            searchMasterMsgAuditLogMapper.add(log);
            // 5.2返回错误信息
            return AjaxResult.me().setSuccess(false).setMessage("审核失败，内容不合法");
        }
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        // 1.获取当前登录人信息
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
        // 2.判断shopId是否为空，不为空则赋值
        if (employee.getShop_id() != null) {
            query.setShopId(employee.getShop_id());
        }
        // 3.返回查询结果
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        // 1.获取当前登录人信息
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.findByLogininfoId(logininfo.getId());
        // 2.设置userId
        query.setUserId(user.getId());
        // 3.返回查询结果
        return super.queryPage(query);
    }

    @Override
    @Transactional
    public void reject(Long id) {
        // 店铺拒单
        searchMasterMsgMapper.reject(id);
    }

    @Override
    @Transactional
    public void accept(Map<String, String> map) throws Exception{
        Long msgId = Long.parseLong(map.get("msgId"));
        Long employeeId = Long.parseLong(map.get("handler"));
        String note = map.get("note");
        // 1.校验当前订单是否已经存在
        OrderPetAcquisition orderPetAcquisition = orderPetAcquisitionMapper.findByMsgId(msgId);
        if (orderPetAcquisition != null && orderPetAcquisition.getState() == 0) {
            throw new BusinessException("订单已经存在，请勿重复接单！");
        }
        // 2.根据寻主消息msgId生成宠物，添加到数据库
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(msgId);
        Pet pet = searchMasterMsg2Pet(searchMasterMsg);
        petMapper.add(pet);
        // 3.生成订单，添加到数据库
        OrderPetAcquisition order = buildOrderPetAcquisition(pet,searchMasterMsg,note,employeeId);
        orderPetAcquisitionMapper.add(order);
        rocketMQTemplate.syncSend("order_topic",
                MessageBuilder.withPayload(order).build(), 3000, 5);
        // 4.发短信通知店铺工作人员去接宠物
        Employee employee = employeeMapper.findById(employeeId);
//        SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请尽快处理!");
        System.out.println("你有新的订单，请尽快处理!");
    }

    private OrderPetAcquisition buildOrderPetAcquisition(Pet pet, SearchMasterMsg searchMasterMsg, String note,Long employeeId) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(searchMasterMsg.getUserId());
        order.setOrderSn(orderSn);
        order.setDigest(searchMasterMsg.getName() + "的收购订单");
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 1000*60*60*24*2));
        order.setState(0);
        order.setPrice(searchMasterMsg.getPrice());
        // paytype支付方式线下支付，现金
        order.setPetId(pet.getId());
        order.setUserId(searchMasterMsg.getUserId());
        order.setShopId(searchMasterMsg.getShopId());
        order.setAddress(searchMasterMsg.getAddress());
        order.setEmpId(employeeId);
        order.setSearchMasterMsgId(searchMasterMsg.getId());
        return order;
    }

    private Pet searchMasterMsg2Pet(SearchMasterMsg searchMasterMsg) {
        Pet pet = new Pet();
        pet.setName(searchMasterMsg.getName());
        pet.setCostprice(searchMasterMsg.getPrice());
        pet.setTypeId(searchMasterMsg.getPetType());
        pet.setResources(searchMasterMsg.getResources());
        pet.setState(0);
        pet.setShopId(searchMasterMsg.getShopId());
        pet.setUserId(searchMasterMsg.getUserId());
        pet.setSearchMasterMsgId(searchMasterMsg.getId());
        return pet;
    }
}
